package com.lucaswangdev.biz.manager.impl;

import com.lucaswangdev.biz.manager.UserManager;
import com.lucaswangdev.constant.common.ErrorConstants;
import com.lucaswangdev.exception.BusinessException;
import com.lucaswangdev.model.convert.UserConverter;
import com.lucaswangdev.model.domain.UserDO;
import com.lucaswangdev.model.domain.UserParam;
import com.lucaswangdev.model.dto.UserDTO;
import com.lucaswangdev.model.mapper.UserMapper;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
public class UserManagerImpl implements UserManager {

    @Resource
    private UserMapper userMapper;

    @Override
    public Long create(UserDTO userDTO) {
        UserDO userDO = UserConverter.INSTANCE.convertDTO2DO(userDTO);
        Date now = new Date();
        userDO.setGmtCreate(now);
        userDO.setGmtModified(now);
        int effectRow = userMapper.insert(userDO);
        if (effectRow != 1) {
            throw new BusinessException(ErrorConstants.CREATE_ERROR.getErrorCode(), ErrorConstants.CREATE_ERROR.getErrorMsg());
        }
        return userDO.getId();
    }

    @Override
    public Long countByParam(UserParam param) {
        return userMapper.countByParam(param);
    }

    @Override
    public List<UserDTO> queryByParam(UserParam param) {
        List<UserDTO> userDTOS = new ArrayList<>();
        List<UserDO> userDOS = userMapper.selectByParam(param);
        if (CollectionUtils.isNotEmpty(userDOS)) {
            userDOS.forEach(userDO -> {
                userDTOS.add(UserConverter.INSTANCE.convertDO2DTO(userDO));
            });
        }
        return userDTOS;
    }

    @Override
    public void update(UserDTO userDTO) {
        UserDO userDO = UserConverter.INSTANCE.convertDTO2DO(userDTO);
        Date now = new Date();
        userDO.setGmtModified(now);
        int effectRow = userMapper.updateByPrimaryKeySelective(userDO);
        if (effectRow != 1) {
            throw new BusinessException(ErrorConstants.UPDATE_ERROR.getErrorCode(), ErrorConstants.UPDATE_ERROR.getErrorMsg());
        }
    }

    @Override
    public void deleteById(Long id) {
        int effectRow = userMapper.deleteByPrimaryKey(id);
        if (effectRow != 1) {
            throw new BusinessException(ErrorConstants.DELETE_ERROR);
        }
    }

    @Override
    public UserDTO queryById(Long id) {
        UserDO userDO = userMapper.selectByPrimaryKey(id);
        if (userDO == null) {
            throw new BusinessException(ErrorConstants.NOT_FOUND_BY_ID, "id: " + id);
        }
        return UserConverter.INSTANCE.convertDO2DTO(userDO);
    }
}
